<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>赛事数据搜索</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        .search-container {
            margin: 20px 0;
        }

        .results-container {
            margin-top: 20px;
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }

        .table th, .table td {
            min-width: 100px;
            vertical-align: middle;
        }

        .loading-container {
            height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .import-btn-container {
            margin-bottom: 15px;
            text-align: right;
        }

        .progress-container {
            margin: 10px 0;
            height: 8px;
            display: none;
        }

        .file-type-hint {
            margin-top: 8px;
            font-size: 0.875rem;
            color: #6c757d;
        }

        .file-type-tags {
            display: inline-flex;
            gap: 5px;
            margin-left: 5px;
        }

        .file-type-tag {
            background-color: #e9ecef;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
        }
    </style>
</head>
<body>
<div class="container mt-4">
    <h1 class="mb-4">赛事数据搜索</h1>

    <!-- 导入按钮区域 -->
    <div class="import-btn-container">
        <button type="button" class="btn btn-success" id="importBtn" data-bs-toggle="modal" data-bs-target="#importModal">
            <i class="bi bi-upload"></i> 导入数据
        </button>
    </div>

    <!-- 搜索框区域 -->
    <div class="search-container card p-4 shadow-sm">
        <div class="row g-3">
            <div class="col-md-10">
                <input type="text" id="searchInput" class="form-control form-control-lg"
                       placeholder="请输入关键词（如队伍名称、比分等）...">
            </div>
            <div class="col-md-2">
                <button id="searchButton" class="btn btn-primary btn-lg w-100">搜索</button>
            </div>
        </div>
    </div>

    <!-- 结果列表区域 -->
    <div class="results-container">
        <div class="card shadow-sm">
            <div class="table-responsive">
                <table class="table table-hover table-striped mb-0">
                    <thead class="table-light">
                    <tr>
                        <th>对阵队伍</th>
                        <th>比赛时间</th>
                        <th>总比分</th>
                        <th>总分差</th>
                        <th>第一节比分</th>
                        <th>第一节分差</th>
                        <th>第二节比分</th>
                        <th>第二节分差</th>
                        <th>上半场分差</th>
                        <th>第三节比分</th>
                        <th>第三节分差</th>
                        <th>第四节比分</th>
                        <th>第四节分差</th>
                        <th>下半场分差</th>
                        <th>加时1比分</th>
                        <th>加时1分差</th>
                        <th>比赛ID</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="resultsTableBody">
                    <tr class="text-center">
                        <td colspan="19" class="py-4">请输入关键词并点击搜索按钮</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 分页控制区域 -->
    <div class="pagination-container">
        <div class="items-per-page">
            <label for="itemsPerPage" class="me-2">每页显示:</label>
            <select id="itemsPerPage" class="form-select" style="width: auto; display: inline-block;">
                <option value="10">10条</option>
                <option value="20">20条</option>
                <option value="50" selected>50条</option>
                <option value="100">100条</option>
            </select>
            <span class="ms-3 text-muted" id="totalInfo">共 0 条数据</span>
        </div>
        <nav>
            <ul class="pagination" id="pagination">
                <!-- 分页按钮动态生成 -->
            </ul>
        </nav>
    </div>
</div>

<!-- 导入数据的模态框 -->
<div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="importModalLabel">导入赛事数据</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 导入说明 -->
                <div class="alert alert-info" role="alert">
                    <p>请上传包含赛事数据的文件，支持Excel和CSV格式</p>
                    <p class="mb-0">文件需包含表头：比赛ID、比赛时间、对阵队伍、各节比分等（与系统字段对应）</p>
                </div>

                <!-- 文件选择 -->
                <div class="mb-3">
                    <label for="dataFile" class="form-label">选择数据文件</label>
                    <input class="form-control" type="file" id="dataFile" accept=".xls,.xlsx,.csv">
                    <div class="file-type-hint">
                        支持的文件格式：
                        <div class="file-type-tags">
                            <span class="file-type-tag">.xls</span>
                            <span class="file-type-tag">.xlsx</span>
                            <span class="file-type-tag">.csv</span>
                        </div>
                        <br>建议单个文件不超过10MB，CSV文件请使用UTF-8编码
                    </div>
                </div>

                <!-- CSV编码选项 (仅CSV文件显示) -->
                <div id="csvEncodingContainer" class="mb-3" style="display: none;">
                    <label for="csvEncoding" class="form-label">CSV文件编码</label>
                    <select class="form-select" id="csvEncoding">
                        <option value="utf-8" selected>UTF-8</option>
                        <option value="gbk">GBK (中文Windows默认)</option>
                        <option value="gb2312">GB2312</option>
                        <option value="utf-16">UTF-16</option>
                    </select>
                </div>

                <!-- 上传进度条 -->
                <div class="progress-container">
                    <div class="progress" role="progressbar" aria-label="上传进度" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                        <div class="progress-bar" style="width: 0%"></div>
                    </div>
                </div>

                <!-- 导入结果提示 -->
                <div id="importResult" class="mt-3" style="display: none;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="uploadBtn" disabled>开始上传</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 全局变量
    let currentPage = 1;
    let itemsPerPage = 50;
    let totalItems = 0;
    let totalPages = 0;

    // DOM元素引用
    const searchInput = document.getElementById('searchInput');
    const searchButton = document.getElementById('searchButton');
    const resultsTableBody = document.getElementById('resultsTableBody');
    const pagination = document.getElementById('pagination');
    const itemsPerPageSelect = document.getElementById('itemsPerPage');
    const totalInfo = document.getElementById('totalInfo');
    // 导入相关元素
    const dataFile = document.getElementById('dataFile');
    const uploadBtn = document.getElementById('uploadBtn');
    const progressContainer = document.querySelector('.progress-container');
    const progressBar = document.querySelector('.progress-bar');
    const importResult = document.getElementById('importResult');
    const importModal = new bootstrap.Modal(document.getElementById('importModal'));
    const csvEncodingContainer = document.getElementById('csvEncodingContainer');
    const csvEncoding = document.getElementById('csvEncoding');

    // 初始化事件监听
    function initEventListeners() {
        // 搜索相关
        searchButton.addEventListener('click', () => {
            currentPage = 1;
            performSearch();
        });
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                currentPage = 1;
                performSearch();
            }
        });
        itemsPerPageSelect.addEventListener('change', (e) => {
            itemsPerPage = parseInt(e.target.value);
            currentPage = 1;
            performSearch();
        });

        // 导入相关
        dataFile.addEventListener('change', handleFileSelection);
        uploadBtn.addEventListener('click', uploadDataFile);
    }

    // 处理文件选择
    function handleFileSelection(e) {
        const file = e.target.files[0];
        uploadBtn.disabled = !file;
        importResult.style.display = 'none';

        if (file && file.name.toLowerCase().endsWith('.csv')) {
            csvEncodingContainer.style.display = 'block';
        } else {
            csvEncodingContainer.style.display = 'none';
        }
    }

    // 执行搜索
    function performSearch() {
        const keyword = searchInput.value.trim();
        showLoading();

        const requestPage = currentPage - 1;
        const url = `/search/doSearch?page=${requestPage}&size=${itemsPerPage}&keyword=${encodeURIComponent(keyword)}`;

        fetch(url)
            .then(response => {
                if (!response.ok) throw new Error('接口请求失败');
                return response.json();
            })
            .then(data => {
                totalItems = data.totalElements || 0;
                totalPages = data.totalPages || 0;
                const results = data.content || [];
                renderTable(results);
                updateTotalInfo();
                updatePagination();
            })
            .catch(error => {
                console.error('搜索出错:', error);
                resultsTableBody.innerHTML = `
                    <tr class="text-center">
                        <td colspan="19" class="py-4 text-danger">数据加载失败，请重试</td>
                    </tr>
                `;
            });
    }

    // 渲染表格（补充所有字段）
    function renderTable(data) {
        resultsTableBody.innerHTML = '';

        if (data.length === 0) {
            resultsTableBody.innerHTML = `
                <tr class="text-center">
                    <td colspan="19" class="py-4">没有找到与"${searchInput.value.trim()}"相关的结果</td>
                </tr>
            `;
            return;
        }

        data.forEach((item, index) => {
            const row = document.createElement('tr');
            const formatValue = (value) => value === null || value === undefined ? '-' : value;

            row.innerHTML = `
                <td>${formatValue(item.projectTeam)}</td>
                <td>${formatValue(item.projectTime)}</td>
                <td>${formatValue(item.projectTotalScore)}</td>
                <td>${formatValue(item.projectTotalDiff)}</td>
                <td>${formatValue(item.projectFirstScore)}</td>
                <td>${formatValue(item.projectFirstDiff)}</td>
                <td>${formatValue(item.projectSecondScore)}</td>
                <td>${formatValue(item.projectSecondDiff)}</td>
                <td>${formatValue(item.firstHalfScoreDiff)}</td>
                <td>${formatValue(item.projectThirdScore)}</td>
                <td>${formatValue(item.projectThirdDiff)}</td>
                <td>${formatValue(item.projectFourthScore)}</td>
                <td>${formatValue(item.projectFourthDiff)}</td>
                <td>${formatValue(item.secondHalfScoreDiff)}</td>
                <td>${formatValue(item.projectAddTimeScore)}</td>
                <td>${formatValue(item.projectAddTimeDiff)}</td>
                <td>${formatValue(item.projectId)}</td>
                <td>
                    <button class="btn btn-sm btn-primary view-btn" data-id="${item.id}">
                        详情
                    </button>
                </td>
            `;
            resultsTableBody.appendChild(row);
        });

        document.querySelectorAll('.view-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const id = btn.getAttribute('data-id');
                alert(`查看ID为${id}的赛事详情`);
            });
        });
    }

    // 更新分页控件
    function updatePagination() {
        pagination.innerHTML = '';

        // 上一页按钮
        const prevBtn = document.createElement('li');
        prevBtn.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        prevBtn.innerHTML = `<a class="page-link" href="javascript:;">上一页</a>`;
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                performSearch();
            }
        });
        pagination.appendChild(prevBtn);

        // 页码按钮（最多显示5个页码）
        const showPageCount = 5;
        let startPage = Math.max(1, currentPage - Math.floor(showPageCount / 2));
        let endPage = startPage + showPageCount - 1;
        if (endPage > totalPages) {
            endPage = totalPages;
            startPage = Math.max(1, endPage - showPageCount + 1);
        }

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('li');
            pageBtn.className = `page-item ${i === currentPage ? 'active' : ''}`;
            pageBtn.innerHTML = `<a class="page-link" href="javascript:;">${i}</a>`;
            pageBtn.addEventListener('click', () => {
                currentPage = i;
                performSearch();
            });
            pagination.appendChild(pageBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('li');
        nextBtn.className = `page-item ${currentPage === totalPages || totalPages === 0 ? 'disabled' : ''}`;
        nextBtn.innerHTML = `<a class="page-link" href="javascript:;">下一页</a>`;
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                performSearch();
            }
        });
        pagination.appendChild(nextBtn);
    }

    // 更新总数据信息
    function updateTotalInfo() {
        totalInfo.textContent = `共 ${totalItems} 条数据，共 ${totalPages} 页`;
    }

    // 显示加载状态
    function showLoading() {
        resultsTableBody.innerHTML = `
            <tr>
                <td colspan="19" class="loading-container">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </td>
            </tr>
        `;
    }

    // 上传数据文件
    function uploadDataFile() {
        const file = dataFile.files[0];
        if (!file) {
            showImportResult('请先选择数据文件', 'danger');
            return;
        }

        // 验证文件大小（限制10MB）
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
            showImportResult('文件过大，请上传不超过10MB的文件', 'danger');
            return;
        }

        // 验证文件类型
        const fileName = file.name.toLowerCase();
        const isExcel = fileName.endsWith('.xls') || fileName.endsWith('.xlsx');
        const isCsv = fileName.endsWith('.csv');

        if (!isExcel && !isCsv) {
            showImportResult('请上传.xls、.xlsx或.csv格式的文件', 'danger');
            return;
        }

        // 准备FormData
        const formData = new FormData();
        formData.append('file', file);

        // 如果是CSV文件，添加编码信息
        if (isCsv) {
            formData.append('encoding', csvEncoding.value);
        }

        // 显示进度条
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        progressBar.setAttribute('aria-valuenow', '0');
        uploadBtn.disabled = true;

        // 发送上传请求
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/search/loadFile', true);

        // 监听上传进度
        xhr.upload.addEventListener('progress', (e) => {
            if (e.lengthComputable) {
                const percent = Math.round((e.loaded / e.total) * 100);
                progressBar.style.width = `${percent}%`;
                progressBar.setAttribute('aria-valuenow', percent);
            }
        });

        // 处理响应
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    const data = JSON.parse(xhr.responseText);
                    if (data.success) {
                        showImportResult(`导入成功！共导入${data.count || 0}条数据`, 'success');
                        // 导入成功后刷新列表
                        setTimeout(() => {
                            importModal.hide();
                            performSearch();
                        }, 1500);
                    } else {
                        showImportResult(`导入失败：${data.message || '未知错误'}`, 'danger');
                        uploadBtn.disabled = false;
                    }
                } catch (error) {
                    showImportResult('导入成功，但解析响应失败', 'warning');
                    setTimeout(() => {
                        importModal.hide();
                        performSearch();
                    }, 1500);
                }
            } else {
                showImportResult(`上传失败，状态码：${xhr.status}`, 'danger');
                uploadBtn.disabled = false;
            }
        };

        // 处理错误
        xhr.onerror = () => {
            showImportResult('网络错误，上传失败', 'danger');
            uploadBtn.disabled = false;
        };

        // 发送请求
        xhr.send(formData);
    }

    // 显示导入结果提示
    function showImportResult(message, type) {
        importResult.textContent = message;
        importResult.className = `alert alert-${type}`;
        importResult.style.display = 'block';
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', initEventListeners);
</script>
</body>
</html>